package com.kotlin.mvpdemo.net.factory;


import androidx.lifecycle.LiveData;

import com.kotlin.mvpdemo.entity.ApiResponse;

import java.lang.reflect.Type;
import java.util.concurrent.atomic.AtomicBoolean;

import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Callback;
import retrofit2.HttpException;
import retrofit2.Response;

/**
 * Created by zf on 2017/9/19.
 */

public class LiveDataCallAdapter<R> implements CallAdapter<R, LiveData<ApiResponse<R>>> {
    private static final String TAG = "LiveDataCallAdapter";
    private final Type responseType;

    public LiveDataCallAdapter(Type responseType) {
        this.responseType = responseType;
    }

    @Override
    public Type responseType() {
        return responseType;
    }

    @Override
    public LiveData<ApiResponse<R>> adapt(final Call<R> call) {
        return new LiveData<ApiResponse<R>>() {
            AtomicBoolean started = new AtomicBoolean(false);

            @Override
            protected void onActive() {
                super.onActive();
                if (started.compareAndSet(false, true)) {
                    call.enqueue(new Callback<R>() {
                        @Override
                        public void onResponse(Call<R> call, Response<R> response) {
                            if (response.isSuccessful()) {
                                postValue(new ApiResponse<>(response));
                            } else {
                                postValue(new ApiResponse(new HttpException(response)));
                            }
                        }
                        @Override
                        public void onFailure(Call<R> call, Throwable t) {
                            postValue(new ApiResponse(t));
                        }
                    });
                }
            }
        };
    }


}


